<?php
/**
 * Created by PhpStorm.
 * User: sunfan
 * Date: 2017/8/12
 * Time: 17:34
 */

namespace User\Controller;


class ParameterController extends ProductController
{
    public function index()
    {
        $pro_id = I('get.pro_id', 0, 'intval');
        $data = $this->model->where(array('id' => $pro_id))
            ->field('id as pro_id,name,map,attrs_key')
            ->find();
        $list = D("Parameter")->where(array('product_id'=>$pro_id))->select();
        $attrs = $data['attrs_key'];
        if($attrs){
            $data['para_name'] =  explode(',',$attrs);
        }
        $this->assign('data',$data);
        $this->assign('list',$list);
        $this->display();
    }

    // 添加规格
    public function add(){
        $post = I("post.",array());
        $data = D("Product")
            ->where(array('id'=>$post['pro_id']))
            ->field("attrs_key,attrs_value")
            ->find();
        $keys = $data['attrs_key']?$data['attrs_key'].','.$post['key']:$post['key'];
        $value = $data['attrs_value']?$data['attrs_value'].','.$post['val']:$post['val'];
        $save = D("Product")
            ->where(array('id'=>$post['pro_id']))
            ->save(array('attrs_key'=>$keys,'attrs_value'=>$value));
        if($save){
          $this->attrReset($post['pro_id'],$keys,$value);
          $list = D("Parameter")->where(array('product_id'=>$post['pro_id']))->select();
          echo json_encode(array('code'=>1,'list'=>$list));
          exit();
        }
    }


    function test(){
        $keys = "颜色,尺寸,款式";
        $vals = "颜|色,x|l|m,长|端|中";
        $this->attrReset(0,$keys,$vals);
    }

    //  重组规格并添加
    private function attrReset($pro_id = 0,$keys,$value){
        D("Parameter")->where(array('product_id'=>$pro_id))->delete();
        $key_arr = explode(",",$keys);
        $val_arr = explode(",",$value);
        $param_keys = array();
        $param_values = array();
        $i = 0;
        foreach($key_arr as $k =>$v){
            $param_val_arr= explode('|',$val_arr[$k]);
            foreach($param_val_arr as $p => $q){
                $param_keys[$k] = $v;
                $param_values[$k][$i] = $q;
                $i++;
            }
        }
        $new_values = $this->repair_data($param_values);
        foreach($new_values as $k => $v){
            $key_str = '';
            $val_str = '';
            $i = 0;
            foreach($v as $val){
                if($i == 0){
                    $val_str .= $val;
                    $key_str .= $param_keys[$i];
                }else{
                    $val_str .= "/".$val;
                    $key_str .= ','.$param_keys[$i];
                }
                $i++;
            }
            $addition = array(
                'product_id'=>$pro_id,
                'attr_title'=>$key_str,
                'attr_value'=>$val_str
            );
            D("Parameter")->where(array('product_id'=>$pro_id))->add($addition);
        }
    }


    private function repair_data($data) {
        $result = array();
        foreach (array_shift($data) as $k=>$item) {
            $result[] = array($k=>$item);
        }

        foreach ($data as $k => $v) {
            $result2 = array();
            foreach ($result as $k1=>$item1) {
                foreach ($v as $k2=>$item2) {
                    $temp     = $item1;
                    $temp[$k2]   = $item2;
                    $result2[] = $temp;
                }
            }
            $result = $result2;
        }
        return $result;
    }

    // 删除规格
    public function delete(){
        $post = I("post.",array());
        $pro_id = $post['pro_id']?$post['pro_id']:0;
        $key = trim($post['attr']);
        $data = $this->model->where(array('id'=>$pro_id))
            ->field("attrs_key,attrs_value")
            ->find();
        $keys = explode(",",$data['attrs_key']);
        $values = explode(",",$data['attrs_value']);
        $new_key = "";
        $new_val = "";
        foreach($keys as $k => $v){
           if(trim($v) != $key){
               $new_key .= $v.",";
               $new_val .= $values[$k].",";
           }
        }
        $new_key = substr($new_key, 0,strripos($new_key,","));
        $new_val = substr($new_val, 0,strripos($new_val,","));

        $save = D("Product")
            ->where(array('id'=>$pro_id))
            ->save(array('attrs_key'=>$new_key,'attrs_value'=>$new_val));
        if($save){
            $this->attrReset($pro_id,$new_key,$new_val);
            $list = D("Parameter")->where(array('product_id'=>$post['pro_id']))->select();
            echo json_encode(array('code'=>1,'list'=>$list));
            exit();
        }
    }

    // 保存所有数据
    public function update(){
        $post = I("post.",array());
        $ids = $post['ids'];
        $stock = $post['stock'];
        $price = $post['price'];
        $price_plus = $post['price_plus'];
        foreach($ids as $k => $id){
           $data =  array(
               'stock' => $stock[$k],
               'price' => $price[$k],
               'price_plus' => $price_plus[$k],
           );
           $save = D("Parameter")->where(array('id'=>$id))->save($data);
        }
        $this->success("保存成功");
    }
}
